package com.xafc.demo.sys.controller.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xafc.demo.sys.model.dto.DeptDto;
import com.xafc.demo.sys.model.entity.Dept;
import com.xafc.demo.framework.result.ApiResult;
import com.xafc.demo.framework.result.PageResult;
import com.xafc.demo.framework.result.ResultCode;
import com.xafc.demo.sys.model.query.DeptPageQuery;
import com.xafc.demo.sys.service.IDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags="部门相关接口")
@RestController
@RequestMapping("/api/sys/dept")
public class DeptApi {

    @Autowired
    private IDeptService deptService;

    @ApiOperation(value = "根据分页获取部门列表")
    @PreAuthorize("hasAuthority('API_SYS_DEPT_LIST')")
    @GetMapping("/list")
    public PageResult<DeptDto> list(DeptPageQuery query){
        Page<DeptDto> page = this.deptService.getDeptList(query);
        return PageResult.success(page);
    }

    @ApiOperation(value = "根据ID获取部门信息")
    @PreAuthorize("hasAuthority('API_SYS_DEPT_UPDATE')")
    @GetMapping("/get/{id}")
    public ApiResult<Dept> detail(@PathVariable("id") Integer id){
        Dept dept = deptService.getDeptById(id);
        return ApiResult.success(dept);
    }

    @ApiOperation(value = "根据IDs获取多个部门信息")
    @GetMapping("/get")
    public ApiResult<List<Dept>> get(@RequestParam("ids") String ids){
        List<Integer> idLists = Arrays.stream(ids.split(",")).map(o -> Integer.valueOf(String.valueOf(o))).collect(Collectors.toList());
        List<Dept> deptList = deptService.getDeptByIds(idLists);
        return ApiResult.success(deptList);
    }

    @ApiOperation(value = "新增部门")
    @PreAuthorize("hasAuthority('API_SYS_DEPT_ADD')")
    @PostMapping("/add")
    public ApiResult add(Dept dept){
        ResultCode resultCode = deptService.addDept(dept);
        return ApiResult.value(resultCode);
    }

    @ApiOperation(value = "更新部门")
    @PreAuthorize("hasAuthority('API_SYS_DEPT_UPDATE')")
    @PostMapping("/update")
    public ApiResult edit(Dept dept){
        ResultCode resultCode = deptService.updateDept(dept);
        return ApiResult.value(resultCode);
    }

    @ApiOperation(value = "删除部门")
    @PreAuthorize("hasAuthority('API_SYS_DEPT_DELETE')")
    @PostMapping("/delete")
    public ApiResult delete(@RequestParam("id") Integer id){
        ResultCode resultCode = deptService.deleteDept(id);
        return ApiResult.value(resultCode);
    }

}
